package com.mutiplethread.demo;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多线程测试
 */
public class MutipleThread {

    public static void main(String[] args) {
        AtomicInteger a = new AtomicInteger(5);
        final int MAX_SIZE=10;

        Thread cus = new Thread(() -> {
            while (true) {
                synchronized (a) {
                    while (a.get() == 0) {
                        try {
                            a.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "消费" + a.get());
                    a.getAndIncrement();
                    a.notifyAll();
                }
            }
        }, "消费者");

        Thread pro = new Thread(() -> {
            while (true) {
                synchronized (a) {
                    while (a.get() == MAX_SIZE) {
                        try {
                            a.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    a.getAndIncrement();
                    System.out.println(Thread.currentThread().getName() + "生产" + a.get());
                    a.notifyAll();
                }
            }
        },"生产者");
        pro.start();
        cus.start();
    }
}
